/*
 * StartApplication.java
 *
 * Created on Jul 22, 2009 2:04:07 PM;
 */

package org.sunspotworld;


import com.sun.spot.core.resources.ResourceUnavailableException;
import com.sun.spot.core.resources.transducers.IIOPin;
import com.sun.spot.core.resources.transducers.ISwitch;
import com.sun.spot.core.util.Utils;
import com.sun.spot.edemo.EDemoBoard;
import edu.ncsu.external_sensors.MaxSonarEZ1UltrasoundSensor;
import edu.ncsu.external_sensors.PINGUltrasoundSensor;
import edu.ncsu.external_sensors.UltrasoundSensor;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

/**
 * Demo Application adapted from Robowulf library
 * @author Douglas McClusky
 */
public class StartApplication extends MIDlet {
    private IIOPin input = EDemoBoard.getInstance().getIOPins()[EDemoBoard.D1];

    protected void startApp() throws MIDletStateChangeException {
        ISwitch sw1 = EDemoBoard.getInstance().getSwitches()[EDemoBoard.SW1];
        PINGUltrasoundSensor ping = new PINGUltrasoundSensor(input, UltrasoundSensor.INCHES);
        MaxSonarEZ1UltrasoundSensor max = new MaxSonarEZ1UltrasoundSensor(input, UltrasoundSensor.INCHES);
        UltrasoundSensor sensor = null;
        if (ping.testConnection()) {
            sensor = ping;
        } else if(max.testConnection()) {
            sensor = max;
        } else {
            System.out.println("No Ultrasound Detected!");
            notifyDestroyed();
        }
        double value;
        while (sw1.isOpen()) {                  // done when switch is pressed
            try {
                value = sensor.getConvertedValue();
                System.out.println("Object " + value + "in. away");
                Utils.sleep(1000);                  // wait 1 second
            } catch (ResourceUnavailableException resourceUnavailableException) {
                resourceUnavailableException.printStackTrace();
            }
        }
        notifyDestroyed();                      // cause the MIDlet to exit
    }

    protected void pauseApp() {
        // This is not currently called by the Squawk VM
    }

    /**
     * Called if the MIDlet is terminated by the system.
     * I.e. if startApp throws any exception other than MIDletStateChangeException,
     * if the isolate running the MIDlet is killed with Isolate.exit(), or
     * if VM.stopVM() is called.
     * 
     * It is not called if MIDlet.notifyDestroyed() was called.
     *
     * @param unconditional If true when this method is called, the MIDlet must
     *    cleanup and release all resources. If false the MIDlet may throw
     *    MIDletStateChangeException  to indicate it does not want to be destroyed
     *    at this time.
     */
    protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
        
    }
}
